// 路由鉴权
import router from "@/router";
import pinia from "./store";
import useUserStore from "@/store/modules/user";
import config from "./config";
// 进度条组件
import nprogress from "nprogress";
import "nprogress/nprogress.css";
import { ElMessage } from "element-plus";

nprogress.configure({ showSpinner: false });
const userStore = useUserStore(pinia);
// 全局前置守卫
router.beforeEach((to, from, next) => {
  // console.log(to, from);
  // 设置标题
  document.title = (config.logo_title + "-" + to.meta.title) as string;
  // 设置进度条
  nprogress.start();

  const token = userStore.token;
  const username = userStore.username;
  // token 存在则登录 否则未登录
  if (token) {
    if (to.path === "/login") {
      next("/");
    } else {
      if (username) {
        next();
      } else {
        userStore
          .userInfo()
          .then(() => {
            next();
          })
          .catch(async err => {
            ElMessage({
              type: "error",
              message: err.message + ",请重新登录"
            });
            await userStore.userLogout();
            next({ path: "/login", query: { redirect: to.path } });
          });
      }
    }
  } else {
    if (to.path === "/login") {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.path } });
    }
  }
});

// 全局后置守卫
router.afterEach((to, from) => {
  nprogress.done();
});

// 未登录 只能访问login 其他重定向到login
// 已登录 其他可以访问 不能访问login 重定向到首页
